$(function() {

	window.curD = new Date();
	window.localVarTemplate = 'ahoireportchromeplugin-template';
	window.localVarDept = 'ahoireportchromeplugin-dept';
	
	var dept = new Array();
	dept.push({id:'801', name:'广深港高铁供电系统（深圳供电段）(TY16026-02-03-20)'});
	dept.push({id:'0', name:'...'});
	dept.push({id:'0', name:'...'});
	dept.push({id:'0', name:'（配置更多部门请联系插件开发者）'});
	window.localStorage.setItem(localVarDept, JSON.stringify(dept));
	
	gen(new Date());
	initTemplateDept();

	$('#data').click(function() {
		var clickDay = $('#selected-date').attr('data');
		if(clickDay == '' || clickDay == null){
			$('#selected-date').css('color','red');
			$('#selected-date').animate({
				'font-size':'16px'
			});
			$('#selected-date').animate({
				'font-size':'14px'
			});
			return false;
		}
		
		if($('#content-div table tr input:checked').length != 1){
			refreshTemplateDiv();
			$('#err-div').fadeIn();
			setTimeout(function(){
				$('#err-div').fadeOut();
			}, 2000);
			$('#template-div').slideDown();
			return false;
		}
		
		var mbo = $('#content-div table tr input:checked').parent().next().text();
		var temp = window.localStorage.getItem(localVarTemplate);
		temp = temp == null ? new Array() : JSON.parse(temp);
		var paramT = new Array();
		$(temp).each(function(i, e){
			if(this.title == mbo){
				paramT = this;
				return false;
			}
		});
		
		chrome.tabs.query({
			active : true,
			currentWindow : true
		}, function(t) {
			chrome.tabs.sendMessage(t[0].id, {
				workDate : clickDay,
				params : paramT
			});
		});
	});
	
	$('#left').click(function(){
		var nd = new Date();
		nd.setFullYear($('#fullyear').text());
		nd.setMonth(parseInt($('#month').text())-1);
		gen(nd);
	});
	$('#right').click(function(){
		var nd = new Date();
		nd.setFullYear($('#fullyear').text());
		nd.setMonth(parseInt($('#month').text())+1);
		gen(nd);
	});
	$('#date-title span').click(function(){
		gen(new Date());
	});
	$('#template').click(function(){
		refreshTemplateDiv();
		$('#template-div').slideToggle();
	});
	$('#t-t-xz').click(function(){
		clearTemplateEdit();
		addNewTemplate();
	});
	$('#t-t-bj').click(function(){
		if(!commonValid()){
			return false;
		}
		
		var mbo = $('#content-div table tr input:checked').parent().next().text();
		clearTemplateEdit();
		initTemplateEdit(mbo);
		addNewTemplate();
	});
	$('#t-t-sc').click(function(){
		if(!commonValid()){
			return false;
		}
		
		var mbo = $('#content-div table tr input:checked').parent().next().text();
		deleteTemplate(mbo);
	});
	$('#t-bc').click(function(){
		saveTemplate();
	});
	$('#t-gb').click(function(){
		hideTemplateDiv();
	});
});

function commonValid(){
	var inputLen = $('#content-div table tr input:checked').length;
	if(inputLen != 1){
		$('#err-div').fadeIn();
		setTimeout(function(){
			$('#err-div').fadeOut();
		}, 2000);
		return false;
	}
	return true;
}

function initTemplateDept(){
	var deptJson = window.localStorage.getItem(localVarDept);
	deptJson = deptJson == null ? new Array() : JSON.parse(deptJson);
	var option = '';
	$(deptJson).each(function(){
		option += '<option value="'+this.id+'">'+this.name+'</option>';
	});
	option = option == '' ? '<option>-未配置-</option>' : option;
	$('#t-xm').html(option); 
}

function clearTemplateEdit(){
	$('input,select').val(''); 
}

function refreshTemplateDiv(){
	var temp = window.localStorage.getItem(localVarTemplate);
	temp = temp == null ? new Array() : JSON.parse(temp);
	
	var htmlText = '<table>'; 
	$(temp).each(function(){
		htmlText += '<tr><td class="radio-td"><input type="radio" name="t-t-radio" /></td><td>'+this.title+'</td></tr>';
	});

	if(temp.length == 0){
		htmlText += '<tr><td>没有找到配置模板！</td></tr>';
	}
	
	htmlText += '</table>';
	
	
	$('#template-div #content-div').html(htmlText);
	
	$('#content-div table tr td:not(.radio-td)').click(function(){
		var c = $(this).parents('tr').find('input:radio').prop('checked');
		$(this).parents('tr').find('input:radio').prop('checked', !c);
	});
}

function addNewTemplate(){
	$('#t-err').hide();
	$('#template-edit-div').slideDown();
}

function saveTemplate(){
	var err = '';
	$('#template-edit-div table input,select').each(function(){
		if($(this).attr('required') != undefined){
			if($(this).val() == '' || $(this).val() == null){
				$(this).focus();
				err = $(this).parents('tr').find('td:eq(0)').text()+'不能为空！';
				return false;
			}
		}
	});
	if(err != ''){
		$('#t-err').text(err).fadeIn();
	}else{
		$('#t-err').fadeOut();
		
		var mbo = $('#t-mb-old').val();
		var mb = $('#t-mb').val();
		
		var temp = window.localStorage.getItem(localVarTemplate);
		temp = temp == null ? new Array() : JSON.parse(temp);
		
		$(temp).each(function(i, e){
			if(this.title == mbo){
				temp.splice(i, 1);
				return false;
			}
		});
		$(temp).each(function(i, e){
			if(this.title == mb){
				temp.splice(i, 1);
				return false;
			}
		});
		
		temp.push({
			title : mb,
			name : $('#t-xm option:selected').text(),
			id : $('#t-xm').val(),
			gs : $('#t-gs').val(),
			dd : $('#t-dd').val(),
			nr : $('#t-nr').val(),
			gj : $('#t-gj').val(),
			bz : $('#t-bz').val()
		});
		window.localStorage.setItem(localVarTemplate, JSON.stringify(temp));
		hideTemplateDiv();
		refreshTemplateDiv();
	}
}

function initTemplateEdit(mbo){
	$('#t-mb-old').val(mbo);
	$('#t-mb').val(mbo);
	
	var temp = window.localStorage.getItem(localVarTemplate);
	temp = temp == null ? new Array() : JSON.parse(temp);
	$(temp).each(function(i, e){
		if(this.title == mbo){
			$('#t-xm option[value='+this.id+']').prop('selected', 'selected');
			$('#t-xm').change();
			$('#t-gs').val(this.gs);
			$('#t-dd').val(this.dd);
			$('#t-nr').val(this.nr);
			$('#t-gj').val(this.gj);
			$('#t-bz').val(this.bz);
			return false;
		}
	});
}

function deleteTemplate(mbo){
	var temp = window.localStorage.getItem(localVarTemplate);
	temp = temp == null ? new Array() : JSON.parse(temp);
	$(temp).each(function(i, e){
		if(this.title == mbo){
			temp.splice(i, 1);
			return false;
		}
	});
	window.localStorage.setItem(localVarTemplate, JSON.stringify(temp));
	refreshTemplateDiv();
}

function hideTemplateDiv(){
	$('#template-edit-div').slideUp();
}

function gen(date){
	$('.week-number').remove();

	var fullYear = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	
	$('#fullyear').text(date.getFullYear());
	$('#month').text(date.getMonth());
	
	$('#date-title span').text(fullYear + '年' + month + '月');
	
	// 本月第一天
	date.setDate(1);
	var firstDay = date.getDate();

	// 第一天周几
	var firstIndex = date.getDay();

	// 本月最后一天
	date.setMonth(date.getMonth() + 1, 1);
	date.setDate(date.getDate() - 1);
	var lastDay = date.getDate();

	// 最后一天周几
	var lastIndex = date.getDay();

	var rowNumber = 0;
	var html = '<div class="date-div week-number">';
	for (var i = 0; i < firstIndex; i++) {
		html += '<div></div>';
		rowNumber++;
	}
	for (var i = firstDay; i <= lastDay; i++) {
		html += '<div class="number ';
		if (i == curD.getDate() && $('#month').text() == curD.getMonth() && $('#fullyear').text() == curD.getFullYear()) {
			html += ' today';
		}
		html += '">' + i + '</div>';
		rowNumber++;
		if (rowNumber % 7 == 0 && !(i == lastDay && lastIndex == 6)) {
			html += '</div><div class="date-div week-number">';
		}
	}
	for (var i = 0; i < 6 - lastIndex; i++) {
		html += '<div></div>';
	}
	html += '</div>';

	$('#date-div').append(html);
	
	$('.week-number div.number').on('click',function() {
		$('.week-number div.number').removeClass('active');
		$(this).addClass('active');
		var date = $(this).text();
		if (date != '') {
			$('#selected-date').css({
				'color':'#35ca2b',
				'font-size':'14px'
			});
			var text = $('#fullyear').text() + '-' + (parseInt($('#month').text())+1) + '-' + date;
			$('#selected-date').text(text);
			$('#selected-date').attr('data', text);
		}
	});
}
